package edu.gu.hajo.gcl.parser;

import edu.gu.hajo.gcl.exception.ParseException;
import edu.gu.hajo.gcl.script.Script;

/**
 * 
 * Parses a complete braces-word i.e. the leading
 * brace is supposed to be there! 
 * 
 * @author hajo
 * @inv nestLevel >= 0
 */
public final class BracesParser  {

	public String parse(Script script) {
		StringBuffer buffer = new StringBuffer();
		
		Parser.parseSpace(script);

		script.next(); // Skip {, ok by pre.
		int nestLevel = 1;
		
		char ch;
		while ((ch = script.next()) != 0) {
			switch (ch) {
			case '{':
				buffer.append(ch);   
				nestLevel++;
				break;
			case '}': // Skip last
				if (nestLevel == 1) { 
					return buffer.toString(); 
				}
				nestLevel--;
			default:
				buffer.append(ch);
			} 
		}
		throw new ParseException(script.getPos() + ": Missing }");
	}
}
